package com.uetoken.cn.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.BindYGPrepareAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.BindYGInfoBean;
import com.uetoken.cn.bean.BindYGPrepareBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author xieyang
 * @date 2018年8月22日17:38:13
 * 绑定优谷账号
 */
public class BindYGActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView  mTvTitle;
    @BindView(R.id.iv_activity_bind_yg_ue)
    ImageView mIvUe;
    @BindView(R.id.iv_activity_bind_yg_yg)
    ImageView mIvYg;
    @BindView(R.id.edt_activity_bind_yg_account)
    EditText  mEdtAccount;
    @BindView(R.id.edt_activity_bind_yg_pwd)
    EditText  mEdtPwd;
    @BindView(R.id.tv_activity_bind_yg_bind)
    TextView  mTvBind;
    /**
     * 网络请求码
     */
    private static final int REQUEST_NETWORK_BIND_YG_PREPARE = 10;
    private static final int REQUEST_NETWORK_BIND_YG         = 20;
    private static final int REQUEST_BIND_YG_INFO = 30;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bind_yg;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        mIvBack.setVisibility(View.VISIBLE);
        mTvTitle.setText(getResources().getString(R.string.str_account_bind));

    }

    @Override
    public void initData() {
        Bitmap ueBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_logo);
        Bitmap ygBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_yougu);
        mIvUe.setImageBitmap(ImageUtils.toRoundCorner(ueBitmap, 10));
        mIvYg.setImageBitmap(ImageUtils.toRoundCorner(ygBitmap, 10));

        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(BindYGActivity.this,ApiHelper.getBindYGInfoUrl(),REQUEST_BIND_YG_INFO,Params.getBindYGInfoPrepareParams());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void init() {

    }


    @OnClick({R.id.iv_back, R.id.tv_activity_bind_yg_bind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_activity_bind_yg_bind:
                bindYGAccount();
                break;
        }
    }

    /**
     * 绑定优谷账号
     */
    private void bindYGAccount() {
        String ygAccount = mEdtAccount.getText().toString().trim();
        String ygPwd = mEdtPwd.getText().toString();
        if (TextUtils.isEmpty(ygAccount)) {
            ToastUtils.showShort(getString(R.string.toast_account_can_not_empty));
            return;
        }
        if (TextUtils.isEmpty(ygPwd)) {
            ToastUtils.showShort(getString(R.string.toast_password_can_not_empty));
            return;
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.bingYGAccountPrepareUrl(), REQUEST_NETWORK_BIND_YG_PREPARE,
                Params.getBindYGAccountPrepareParams(ygAccount, EncodeUtils.base64Encode2String(ygPwd.getBytes())));
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        dissmissDialog();

        switch (requestCode) {
            case REQUEST_NETWORK_BIND_YG_PREPARE:
                BindYGPrepareBean bindYGPrepareBean = new Gson().fromJson(response, BindYGPrepareBean.class);
                if (bindYGPrepareBean.getResult() > 0) {
                    View view = View.inflate(BindYGActivity.this, R.layout.dialog_bind_yg, null);
                    final Dialog dialog = new Dialog(BindYGActivity.this, R.style.Theme_AppCompat_Dialog);
                    dialog.setContentView(view);
                    dialog.setCancelable(false);
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
   /*                 WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                    params.width = ScreenUtils.getScreenWidth()/2;
                    dialog.getWindow().setAttributes(params);
*/
                    ViewHolder viewHolder = new ViewHolder(view);
                    if (bindYGPrepareBean.getData().getPurseinfo().size() > 0) {
                        viewHolder.mRyYg.setLayoutManager(new LinearLayoutManager(BindYGActivity.this, LinearLayoutManager.VERTICAL, false));

                        List<BindYGPrepareBean.DataBean.PurseinfoBean> list = bindYGPrepareBean.getData().getPurseinfo();
                        Iterator<BindYGPrepareBean.DataBean.PurseinfoBean> iterator = list.iterator();
                        while (iterator.hasNext()){
                            BindYGPrepareBean.DataBean.PurseinfoBean purseinfoBean = iterator.next();
                            if (purseinfoBean.getBalance()==0){
                                //移除掉余额为0的情况
                                iterator.remove();
                            }
                        }
                        if (list.size()==0){
                            viewHolder.mRyYg.setVisibility(View.GONE);
                            viewHolder.mIvNotData.setVisibility(View.VISIBLE);
                            viewHolder.mTvNotSyncData.setVisibility(View.VISIBLE);
                            viewHolder.mTvSycNow.setClickable(false);
                            viewHolder.mTvSycNow.setBackgroundColor(Color.parseColor("#98B3FF"));
                        }else{
                            viewHolder.mIvNotData.setVisibility(View.GONE);
                            viewHolder.mTvNotSyncData.setVisibility(View.GONE);
                            viewHolder.mRyYg.setVisibility(View.VISIBLE);

                            BindYGPrepareAdapter bindYGPrepareAdapter = new BindYGPrepareAdapter(R.layout.item_bind_yg_prepare, list);
                            viewHolder.mRyYg.setAdapter(bindYGPrepareAdapter);

                            final String nodeCode = bindYGPrepareBean.getData().getNodecode();

                            viewHolder.mTvSycNow.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                    String ygPwd = mEdtPwd.getText().toString();
                                    showLoading();
                                    OkHttpUtils.getInstance().getStringWithParam(BindYGActivity.this, ApiHelper.bindYGAccountUrl(), REQUEST_NETWORK_BIND_YG,
                                            Params.getBindYGAccountParams(nodeCode, EncodeUtils.base64Encode2String(ygPwd.getBytes())));
                                }
                            });
                        }

                    } else {
                        viewHolder.mRyYg.setVisibility(View.GONE);
                        viewHolder.mIvNotData.setVisibility(View.VISIBLE);
                        viewHolder.mTvNotSyncData.setVisibility(View.VISIBLE);
                        viewHolder.mTvSycNow.setClickable(false);
                        viewHolder.mTvSycNow.setBackgroundColor(Color.parseColor("#98B3FF"));
                    }
                    viewHolder.mTvCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                }else{
                    ToastUtils.showShort(bindYGPrepareBean.getMessage());
                }
                break;
            case REQUEST_NETWORK_BIND_YG:
                JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
                if (obj.get("result").getAsInt() > 0) {
                    ActivityUtils.finishActivity(MainActivity.class);
                    startActivity(new Intent(BindYGActivity.this, MainActivity.class));
                    finish();
                }
                ToastUtils.showShort(obj.get("message").getAsString());
                break;
            case REQUEST_BIND_YG_INFO:
                BindYGInfoBean bindYGInfoBean = new Gson().fromJson(response,BindYGInfoBean.class);
                if (bindYGInfoBean.getResult()>0){
                    if (bindYGInfoBean.getData()!=null){
                        String nodeCode = bindYGInfoBean.getData().getNodecode();
                        mEdtAccount.setText(nodeCode);
                        mEdtAccount.setFocusable(false);
                    }else{
                        ToastUtils.showShort(bindYGInfoBean.getMessage());
                    }
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        ToastUtils.showShort(e.getMessage());
    }

    static class ViewHolder {
        @BindView(R.id.ry_dialog_bind_yg)
        RecyclerView mRyYg;
        @BindView(R.id.iv_dialog_bind_yg_not_data)
        ImageView    mIvNotData;
        @BindView(R.id.tv_dialog_bind_yg_cancel)
        TextView     mTvCancel;
        @BindView(R.id.tv_dialog_bind_yg_syc_now)
        TextView     mTvSycNow;
        @BindView(R.id.tv_dialog_bind_yg_not_sync_data)
        TextView     mTvNotSyncData;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

